package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.myprofile

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaMyProfileBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import org.json.JSONObject

class MyProfileGhanaDetailActivity : AppCompatActivity() {

    private lateinit var myProfileViewModel: MyProfileGhanaViewModel
    private lateinit var binding: ActivityGhanaMyProfileBinding
    private lateinit var adapter: MyProfileGhanaDetailPageAdapter

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        myProfileViewModel = ViewModelProvider(this)[MyProfileGhanaViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaMyProfileBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.navbarRight
        val navbarTitle = binding.navbarTitle
        val back = binding.navbarLeft
        val list = binding.list
        val loading = binding.loading

        // 初始化adapter
        adapter =
            MyProfileGhanaDetailPageAdapter(emptyList(), object : MyProfileGhanaDetailPageListener {
                override fun onClick(step: String) {
                    // 查看详情
                }
            })
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 页面loading状态接口监听
        myProfileViewModel.loadingResult.observe(this@MyProfileGhanaDetailActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面UI状态接口监听
        myProfileViewModel.pageDetailResult.observe(this@MyProfileGhanaDetailActivity, Observer {
            val pageDetailResult = it ?: return@Observer
            loading.visibility = View.GONE

            if (pageDetailResult.error != null) {
                showMessage(pageDetailResult.error)
            }
            if (pageDetailResult.items != null) {
                // 渲染
                adapter.dataList = pageDetailResult.items
                adapter.notifyDataSetChanged()
            }
        })

        // 流程接口监听
        myProfileViewModel.mainProcessResult.observe(this@MyProfileGhanaDetailActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                myProfileViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        myProfileViewModel.nextRouterResult.observe(this@MyProfileGhanaDetailActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 判断是否需要拉取数据
        val stepTitle = intent.getStringExtra("stepTitle") ?: ""
        navbarTitle.text = stepTitle

        val step = intent.getStringExtra("step") ?: ""
        if (step.isBlank()) {
            finish()
            return
        }
        getPageDetailByStep(step)
    }

    private fun getPageDetailByStep(step: String) {
        binding.loading.visibility = View.VISIBLE
        myProfileViewModel.pageDetailByStep(step = step)
    }

    fun showMessage(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }
}

interface MyProfileGhanaDetailPageListener {
    fun onClick(step: String)
}

class MyProfileGhanaDetailPageAdapter(
    var dataList: List<JSONObject>,
    var onClick: MyProfileGhanaDetailPageListener? = null
) :
    RecyclerView.Adapter<MyProfileGhanaDetailPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_ghana_my_profile_detail_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val title: TextView = view.findViewById(R.id.title)
        val detail: TextView = view.findViewById(R.id.detail)
        private val topLine: View = view.findViewById(R.id.topLine)

        fun bindData(item: JSONObject) {
            title.text = item.optString("showTitle")
            detail.text = item.optString("showDetail")

            val isTitle = item.optString("title") == "YES"
            if (isTitle) {
                topLine.visibility = View.VISIBLE
            } else {
                topLine.visibility = View.GONE
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}